package com.tl.web04.controller;

import com.alibaba.fastjson.JSONObject;
import com.tl.web04.config.Config;
import com.tl.web04.constant.ResponseResult;
import com.tl.web04.model.entity.User;
import com.tl.web04.service.LoginAndRegisterService;
import com.tl.web04.utils.DateUtil;
import com.tl.web04.utils.JsonParamUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;

@WebServlet(name = "AjaxRegisterServlet", value = "/ajax_register")
public class AjaxRegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取参数
            JSONObject jsonParam = JsonParamUtil.getJsonParam(request);
            String username = jsonParam.getString("username");
            String password = jsonParam.getString("password");
            String nickname = jsonParam.getString("nickname");
            String age = jsonParam.getString("age");
            String birthday = jsonParam.getString("birthday");
            //配置响应编码
            request.setCharacterEncoding(Config.REQ_ChARSET);
            response.setContentType(Config.RESP_JSON_CONTENT_TYPE);
            //获取输出
            PrintWriter out = response.getWriter();
            //获取全局域
            ServletContext application = request.getServletContext();
            //注册的方法
            ResponseResult result = null;
            try {
                User user = new User(username,password,nickname,Integer.parseInt(age), DateUtil.parase(birthday,DateUtil.DATEFORMATDAY));
                result = LoginAndRegisterService.register(application,user);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //向页面输出响应
            out.print(JSONObject.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

    }
}
